package ferp.android.social.twvk.tw;

import android.net.Uri;
import android.os.Bundle;
import ferp.android.social.twvk.Account;
import ferp.android.social.twvk.LoginActivity;
import ferp.core.log.Log;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;

/**
 * User: olegs
 * Date: 5/14/13 10:08 AM
 */
public class TwLoginActivity extends LoginActivity
{
  @Override
  protected void onCreate(Bundle savedInstanceState)
  {
    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setOAuthConsumerKey(TwConnector.TWITTER_CONSUMER_KEY);
    builder.setOAuthConsumerSecret(TwConnector.TWITTER_CONSUMER_SECRET);
    Configuration configuration = builder.build();

    TwitterFactory factory = new TwitterFactory(configuration);
    twitter = factory.getInstance();

    try
    {
      requestToken = twitter.getOAuthRequestToken(TwConnector.TWITTER_CALLBACK_URL);
    }
    catch (TwitterException e)
    {
      Log.error(TwConnector.TAG, e);
    }

    super.onCreate(savedInstanceState);
  }

  @Override
  protected String getTag()
  {
    return TwConnector.TAG;
  }

  @Override
  protected String getAuthUrl()
  {
    return requestToken == null ? null : requestToken.getAuthenticationURL();
  }

  @Override
  protected Account parseRedirectUrl(String url) throws Exception
  {
    Uri uri = Uri.parse(url);

    String verifier = uri.getQueryParameter(TwConnector.URL_TWITTER_OAUTH_VERIFIER);

    AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);

    return new Account(accessToken.getToken(), accessToken.getTokenSecret());
  }

  @Override
  protected String getUrlPrefix()
  {
    return TwConnector.TWITTER_CALLBACK_URL;
  }

  private Twitter twitter;
  private RequestToken requestToken;
}
